# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 教练视图

教练管理相关的路由处理
包括教练CRUD操作、审核、统计等功能
"""

from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user
from app.forms.coach_forms import (
    CoachSearchForm, CoachEditForm, CoachApprovalForm,
    CoachProfileForm, CoachBatchForm, CoachDeleteForm
)
from app.controllers.coach_controller import CoachController
from app.utils.decorators import admin_required, super_admin_required

# 创建教练蓝图
coaches_bp = Blueprint('coaches', __name__)


@coaches_bp.route('/')
@coaches_bp.route('/list')
@admin_required
def list():
    """
    教练列表页

    支持搜索、筛选、分页功能
    """
    form = CoachSearchForm()

    # 获取搜索参数
    page = request.args.get('page', 1, type=int)
    keyword = request.args.get('keyword', '')
    campus_id = request.args.get('campus_id', '', type=str)
    status = request.args.get('status', '')
    coach_level = request.args.get('coach_level', '')
    sort_by = request.args.get('sort_by', 'created_at_desc')

    # 转换campus_id
    campus_id = int(campus_id) if campus_id and campus_id.isdigit() else None

    # 设置表单默认值
    if request.method == 'GET':
        form.keyword.data = keyword
        form.campus_id.data = campus_id
        form.status.data = status
        form.coach_level.data = coach_level
        form.sort_by.data = sort_by

    # 获取教练列表
    pagination, total = CoachController.get_coach_list(
        page=page,
        per_page=12,
        keyword=keyword,
        campus_id=campus_id,
        status=status,
        coach_level=coach_level,
        sort_by=sort_by
    )

    # 获取汇总统计
    summary = CoachController.get_campus_coach_summary(campus_id)

    return render_template(
        'coaches/list.html',
        form=form,
        pagination=pagination,
        coaches=pagination.items,
        total=total,
        summary=summary
    )


@coaches_bp.route('/<int:id>')
@admin_required
def detail(id):
    """
    教练详情页

    显示教练完整信息和统计数据
    """
    coach = CoachController.get_coach_by_id(id)
    if not coach:
        flash('教练不存在或无权限访问', 'error')
        return redirect(url_for('coaches.list'))

    # 获取教练统计信息
    statistics = CoachController.get_coach_statistics(id)

    # 获取学员列表
    students = CoachController.get_coach_students(id)

    # 获取最近的预约记录
    recent_reservations = CoachController.get_coach_recent_reservations(id)

    return render_template(
        'coaches/detail.html',
        coach=coach,
        statistics=statistics,
        students=students,
        recent_reservations=recent_reservations
    )


@coaches_bp.route('/<int:id>/edit', methods=['GET', 'POST'])
@admin_required
def edit(id):
    """
    编辑教练页

    校区管理员可以编辑自己校区的教练
    超级管理员可以编辑任意教练
    """
    coach = CoachController.get_coach_by_id(id)
    if not coach:
        flash('教练不存在或无权限访问', 'error')
        return redirect(url_for('coaches.list'))

    form = CoachEditForm(coach=coach)

    if request.method == 'GET':
        # 填充表单数据
        form.real_name.data = coach.real_name
        form.phone.data = coach.phone
        form.email.data = coach.email
        form.gender.data = coach.gender
        form.age.data = coach.age
        form.campus_id.data = coach.campus_id
        form.coach_level.data = coach.coach_level
        form.hourly_rate.data = coach.hourly_rate
        form.bio.data = coach.bio
        form.experience.data = coach.experience
        form.status.data = coach.status

    if request.method == 'POST':
        if form.validate_on_submit():
            # 获取表单数据
            form_data = {
                'real_name': form.real_name.data,
                'phone': form.phone.data,
                'email': form.email.data,
                'gender': form.gender.data,
                'age': form.age.data,
                'campus_id': form.campus_id.data,
                'coach_level': form.coach_level.data,
                'hourly_rate': form.hourly_rate.data,
                'bio': form.bio.data,
                'experience': form.experience.data,
                'status': form.status.data,
                'photo': form.photo.data
            }

            # 更新教练
            success, error_msg = CoachController.update_coach(coach, form_data)

            if success:
                flash(f'教练"{coach.real_name}"信息更新成功！', 'success')
                return redirect(url_for('coaches.detail', id=coach.id))
            else:
                flash(f'更新失败：{error_msg}', 'error')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(f'{form[field].label.text}: {error}', 'error')

    return render_template('coaches/edit.html', form=form, coach=coach)


@coaches_bp.route('/<int:id>/approve', methods=['GET', 'POST'])
@admin_required
def approve(id):
    """
    教练审核页

    审核待审核状态的教练
    """
    coach = CoachController.get_coach_by_id(id)
    if not coach:
        flash('教练不存在或无权限访问', 'error')
        return redirect(url_for('coaches.list'))

    if coach.status != 'pending':
        flash('该教练已经被审核过了', 'warning')
        return redirect(url_for('coaches.detail', id=id))

    form = CoachApprovalForm()
    form.coach_id.data = id

    if request.method == 'POST':
        if form.validate_on_submit():
            # 获取表单数据
            form_data = {
                'action': form.action.data,
                'campus_id': form.campus_id.data,
                'coach_level': form.coach_level.data,
                'hourly_rate': form.hourly_rate.data,
                'response_note': form.response_note.data
            }

            # 审核教练
            success, error_msg = CoachController.approve_coach(id, form_data)

            if success:
                action_text = '通过' if form.action.data == 'approve' else '拒绝'
                flash(f'教练"{coach.real_name}"审核{action_text}成功！', 'success')
                return redirect(url_for('coaches.detail', id=id))
            else:
                flash(f'审核失败：{error_msg}', 'error')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(f'{form[field].label.text}: {error}', 'error')

    return render_template('coaches/approve.html', form=form, coach=coach)


@coaches_bp.route('/<int:id>/profile', methods=['GET', 'POST'])
@login_required
def profile(id):
    """
    教练档案页

    教练可以编辑自己的档案信息
    管理员可以查看教练档案
    """
    coach = CoachController.get_coach_by_id(id)
    if not coach:
        flash('教练不存在或无权限访问', 'error')
        return redirect(url_for('coaches.list'))

    # 权限检查：只有教练本人或管理员可以访问
    if not (current_user.id == id or current_user.is_super_admin() or current_user.is_campus_admin()):
        flash('无权限访问此页面', 'error')
        return redirect(url_for('dashboard.index'))

    # 教练本人可以编辑，管理员只能查看
    can_edit = (current_user.id == id)

    if can_edit:
        form = CoachProfileForm()

        if request.method == 'GET':
            form.bio.data = coach.bio
            form.experience.data = coach.experience

        if request.method == 'POST':
            if form.validate_on_submit():
                # 获取表单数据
                form_data = {
                    'bio': form.bio.data,
                    'experience': form.experience.data,
                    'photo': form.photo.data
                }

                # 更新档案
                success, error_msg = CoachController.update_coach(coach, form_data)

                if success:
                    flash('档案更新成功！', 'success')
                    return redirect(url_for('coaches.profile', id=id))
                else:
                    flash(f'更新失败：{error_msg}', 'error')
            else:
                for field, errors in form.errors.items():
                    for error in errors:
                        flash(f'{form[field].label.text}: {error}', 'error')
    else:
        form = None

    # 获取统计信息
    statistics = CoachController.get_coach_statistics(id)

    return render_template(
        'coaches/profile.html',
        coach=coach,
        form=form,
        can_edit=can_edit,
        statistics=statistics
    )


@coaches_bp.route('/batch', methods=['POST'])
@admin_required
def batch_operation():
    """
    批量操作教练

    支持批量状态更新、级别设置、校区转移等
    """
    form = CoachBatchForm()

    if form.validate_on_submit():
        try:
            coach_ids = [int(id.strip()) for id in form.coach_ids.data.split(',') if id.strip()]
            action = form.action.data

            kwargs = {}
            if action == 'set_level':
                kwargs['target_level'] = form.target_level.data
            elif action == 'transfer_campus':
                kwargs['target_campus_id'] = form.target_campus_id.data

            success_count, fail_count, errors = CoachController.batch_operation(
                coach_ids, action, **kwargs
            )

            # 构建结果消息
            if success_count > 0:
                action_text = {
                    'activate': '激活',
                    'deactivate': '停用',
                    'delete': '删除',
                    'set_level': '设置级别',
                    'transfer_campus': '转移校区'
                }.get(action, '操作')
                flash(f'成功{action_text}{success_count}个教练', 'success')

            if fail_count > 0:
                flash(f'{fail_count}个教练操作失败', 'warning')
                for error in errors[:5]:  # 只显示前5个错误
                    flash(error, 'error')

        except Exception as e:
            flash(f'批量操作失败：{str(e)}', 'error')
    else:
        # 显示表单验证错误
        for field, errors in form.errors.items():
            for error in errors:
                flash(error, 'error')

    return redirect(url_for('coaches.list'))


@coaches_bp.route('/api/search')
@admin_required
def api_search():
    """
    教练搜索API

    用于AJAX请求获取教练列表
    """
    keyword = request.args.get('keyword', '')
    campus_id = request.args.get('campus_id', '', type=str)
    campus_id = int(campus_id) if campus_id and campus_id.isdigit() else None
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 12, type=int)

    try:
        pagination, total = CoachController.get_coach_list(
            page=page,
            per_page=per_page,
            keyword=keyword,
            campus_id=campus_id
        )

        coaches_data = []
        for coach in pagination.items:
            coaches_data.append({
                'id': coach.id,
                'real_name': coach.real_name,
                'phone': coach.phone,
                'campus_name': coach.campus.name if coach.campus else '',
                'coach_level': coach.coach_level,
                'coach_level_display': {
                    'senior': '高级教练',
                    'middle': '中级教练',
                    'junior': '初级教练'
                }.get(coach.coach_level, ''),
                'hourly_rate': float(coach.hourly_rate) if coach.hourly_rate else None,
                'status': coach.status,
                'status_display': {
                    'active': '在职',
                    'inactive': '离职',
                    'pending': '待审核'
                }.get(coach.status, ''),
                'created_at': coach.created_at.strftime('%Y-%m-%d') if coach.created_at else ''
            })

        return jsonify({
            'success': True,
            'data': coaches_data,
            'pagination': {
                'page': pagination.page,
                'pages': pagination.pages,
                'per_page': pagination.per_page,
                'total': pagination.total,
                'has_prev': pagination.has_prev,
                'has_next': pagination.has_next
            }
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@coaches_bp.route('/api/<int:id>/statistics')
@admin_required
def api_statistics(id):
    """
    教练统计API

    获取教练的统计信息
    """
    coach = CoachController.get_coach_by_id(id)
    if not coach:
        return jsonify({'success': False, 'error': '教练不存在或无权限访问'}), 404

    try:
        statistics = CoachController.get_coach_statistics(id)
        return jsonify({
            'success': True,
            'data': statistics
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@coaches_bp.route('/api/summary')
@admin_required
def api_summary():
    """
    教练汇总统计API

    获取校区的教练汇总信息
    """
    campus_id = request.args.get('campus_id', '', type=str)
    campus_id = int(campus_id) if campus_id and campus_id.isdigit() else None

    try:
        summary = CoachController.get_campus_coach_summary(campus_id)
        return jsonify({
            'success': True,
            'data': summary
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@coaches_bp.route('/api/pending-count')
@admin_required
def api_pending_count():
    """
    待审核教练数量API

    获取待审核的教练数量
    """
    try:
        count = CoachController.get_pending_coaches_count()
        return jsonify({
            'success': True,
            'data': {'pending_count': count}
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500